package com.task.listen;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.entity.Task;
import com.entity.Terminal;
import com.interfaces.TaskDao;
import com.task.job.meter3761.MeterHourse;
import com.task.job.system.GetRecharge;
import com.task.manage.JobManage;
import com.task.manage.Job_Server;
import com.task.service.TaskService;

@WebListener
public class JobListen implements ServletContextListener {

	private Logger logger = Logger.getLogger(JobListen.class);

	@Value("${task.costcontrol.cron}")
	private String cron;

	@Autowired
	private JobManage taskManage;

	@Autowired
	private Job_Server job_server;

	@Autowired
	private TaskDao taskDao;

	@Autowired
	private TaskService taskService;
	@Autowired
	private GetRecharge getRecharge;
	@Autowired
	private MeterHourse meterHourse;

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// 加载默认任务
		taskManage.addjob("recharge", getRecharge, "recharge", "system", cron, "2017-01-01 00:00:00",
				"2018-01-01 00:00:00", "");
		// 查询数据库
		List<Task> tasks = taskDao.findByTaskstatus("1");
		// 根据数据库的job内容，添加后台任务
		for (Task task : tasks) {

			List<Terminal> terminals = taskService.listTerminalByTaskid(Integer.valueOf(task.getTaskid()));

			for (Terminal terminal : terminals) {
				logger.info(terminal.getTerminalid());
				job_server.Jobadd(Integer.valueOf(task.getTasktype()), task.getJobtype(),
						String.valueOf(task.getTaskid()), task.getCron(), task.getTaskbegin(), task.getTaskend(),
						String.valueOf(terminal.getTerminalid()));
			}

		}

		// 启动任务
		try {
			taskManage.start();
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// 关闭所有任务
		try {
			taskManage.shutdown();
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
